<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <script src="https://unpkg.com/vue"></script>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.1/animate.min.css" />
  <style>
    * {
      margin: 0;
      padding: 0;
    }

    .container {
      position: absolute;
      width: 200px;
      height: 400px;
      background-color: pink;
      left: 50%;
      top: 50%;
      transform: translate(-50%, -50%);
    }
  </style>
</head>

<body>
  <div id="root"></div>
  <script>
    /* 
      1. 数据校验插件示例
      - rules中对data数据进行校验
      - 控制台中修改数据值查看校验结果
      2. 通过混入对象实现
      3. 通过插件+混入对象实现
    */

    const app = Vue.createApp({
      template: `
      <div class="container" >
        {{name}} -- {{age}}
      </div>
    `,
      data() {
        return {
          name: 'lxw',
          age: 33
        }
      },
      rules: {
        age: {
          validate: age => age > 25,
          message: '太年轻了'
        }
      }
    })
    const dataValidatePlugin = {
      /*
        1. 参数一 Vue实例
        2. 参数二 使用插件时传入的参数
      */
      install(app, options) {
        app.mixin({
          created() {
            for (let key in this.$options.rules) {
              const item = this.$options.rules[key]
              this.$watch(key, value => {
                const result = item.validate(value)
                if (!result) alert(item.message)
              })
            }
          }
        })
      }
    }
    app.use(dataValidatePlugin)
    const vm = app.mount('#root');

  </script>
</body>

</html>